// Ajax Client Library

AjaxClient = function() {}

AjaxClient.initClient = function() {
    if (window.XMLHttpRequest)
	return new XMLHttpRequest();
    var types = [
		 "Microsoft.XMLHTTP",
		 "MSXML2.XMLHTTP.5.0",
		 "MSXML2.XMLHTTP.4.0",
		 "MSXML2.XMLHTTP.3.0",
		 "MSXML2.XMLHTTP"
    ];
    for (var i in types) {
	try {
	    return new ActiveXObject(types[i]);
	} catch(e) {}
    }
    return null;
}

AjaxClient.call = function(param) {
    var uri = param['uri'];
    if (!uri) return;
    var c = AjaxClient.initClient();
    if (!c) return;
    var method = param['method'].toUpperCase() || 'GET';
    // add random bits to avoid caching in some UA
    uri += (uri.match(/\?/) ? '&' : '?') + '.r=' + Math.random(1);
    var content = null;
    if (param['args']) {
	var args = new Array();
	for (var a in param['args'])
	    args.push(a + '=' + encodeURIComponent(param['args'][a]));
	content = args.join('&');
    }
    if (content && method == 'GET') {
	uri += '&' + content;
	content = null;
    }
    c.open(method, uri, true);
    c.onreadystatechange = function() {
	switch (c.readyState) {
	case 1:
	    if (param['loading']) param['loading'](c);
	    break;
	case 2:
	    if (param['loaded']) param['loaded'](c);
	    break;
	case 3:
	    if (param['interactive']) param['interactive'](c);
	    break;
	case 4:
	    if (c.status && (c.status != 200)) {
		if (param['error'])
		    param['error'](c, c.responseText);
                else
		    alert('Error: [' + c.status + '] ' + c.responseText);
	    } else if (param['load'])
		param['load'](c, c.responseText);
	    break;
	}
    };
    if (content)
	c.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    c.send(content);
}
